
package com.netease.xone.fragment;

import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.XoneServiceCode;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.X1LoadingAdapterViewBase.OnLoadingListener;
import com.netease.pkgRelated.XoneConsts;
import com.netease.xone.R;
import com.netease.xone.adapter.AdapterInfo;
import com.netease.xone.widget.listview.LoadingListView;

import db.XoneDBTables.AppInfoTable;
import db.manager.ManagerAccount;
import db.manager.ManagerAppInfo;

/**
 * 支持的资讯类型see {@link InfoListType}
 * @author MR
 *
 */
public class FragmentInfoList extends FragmentBase implements LoaderCallbacks<Cursor> {

    public enum InfoListType {
        pop_discuss// 最热讨论
        , guess_discuss// 讨论-猜你喜欢
        , topic_discuss// 话题下讨论
    }

    // Views
    private LoadingListView mLoadingList;
    private AdapterInfo mAdapter;
    // Data
    private InfoListType mType;
    private long mTopicId;
    private int mCurrentPage;
    // Tid
    private int mTid;

    public static FragmentInfoList newInstance(InfoListType type) {
        return newInstance(type, -1);
    }

    public static FragmentInfoList newInstance(InfoListType type, long topicId) {
        FragmentInfoList f = new FragmentInfoList();
        Bundle b = new Bundle();
        b.putSerializable(XoneConsts.BUNDLE_KEY.INFO_LIST_TYPE, type);
        if (topicId != -1) {
            b.putLong(XoneConsts.BUNDLE_KEY.TOPIC_ID, topicId);
        }
        f.setArguments(b);
        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mType = (InfoListType)getArguments().getSerializable(XoneConsts.BUNDLE_KEY.INFO_LIST_TYPE);
        if (mType == InfoListType.topic_discuss) {
            mTopicId = getArguments().getLong(XoneConsts.BUNDLE_KEY.TOPIC_ID);
        }
        setHasOptionsMenu(true);
        XoneService.getInstance().addListener(mCallBack);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.view_loading_listview, null);
        mAdapter = new AdapterInfo(getActivity(), null);
        mLoadingList = (LoadingListView)view;
        mLoadingList.setAdapter(mAdapter);
        mLoadingList.disablePullToRefresh();
        mLoadingList.setOnLoadingListener(new OnLoadingListener() {

            @Override
            public void onRefreshing() {

            }

            @Override
            public void onLoading() {
                mCurrentPage = 1;
                switch (mType) {
                    case pop_discuss:
                        mTid = XoneService.getInstance().doGetPopDiscussList(1,
                                XoneConsts.LIST_ITEM_COUNT.ONE_REQUEST_COUNT);
                        break;
                    case guess_discuss:
                        mTid = XoneService.getInstance().doGetGuessDiscussList(1,
                                XoneConsts.LIST_ITEM_COUNT.ONE_REQUEST_COUNT);
                        break;
                    case topic_discuss:
                        mTid = XoneService.getInstance().doGetTopicInfoList(mTopicId, mCurrentPage,
                                XoneConsts.LIST_ITEM_COUNT.ONE_REQUEST_COUNT);
                        break;
                }
            }

            @Override
            public void onLoadingMore() {
                mCurrentPage ++;
                switch (mType) {
                    case topic_discuss:
                        mTid = XoneService.getInstance().doGetTopicInfoList(mTopicId, mCurrentPage,
                                XoneConsts.LIST_ITEM_COUNT.ONE_REQUEST_COUNT);
                        break;
                    default://do nothing
                }
            }
        });
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getLoaderManager().initLoader(0, null, this);
        mLoadingList.load();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        XoneService.getInstance().removeListener(mCallBack);
    }

    private XoneCallBack mCallBack = new XoneCallBack() {

        @Override
        public void onGetPopDiscussList(int transactionId) {
            if (mTid == transactionId) {
                mLoadingList.onLoadingComplete(false);
            }
        };

        @Override
        public void onGetPopDiscussListError(int transactionId, int errCode, String err) {
            if (mTid == transactionId) {
                if (errCode == XoneServiceCode.NETWORK_ERR_COMMON) {
                    mLoadingList.onNoNetwork();
                } else {
                    mLoadingList.onLoadingError();
                }
            }
        };

        @Override
        public void onGetGuessDiscussList(int transactionId) {
            if (mTid == transactionId) {
                mLoadingList.onLoadingComplete(false);
            }
        };

        @Override
        public void onGetGuessDiscussListError(int transactionId, int errCode, String err) {
            if (mTid == transactionId) {
                if (errCode == XoneServiceCode.NETWORK_ERR_COMMON) {
                    mLoadingList.onNoNetwork();
                } else {
                    mLoadingList.onLoadingError();
                }
            }
        };

        @Override
        public void onGetTopicDiscussList(int transactionId, boolean hasMore) {
            if (mTid == transactionId) {
                mLoadingList.onLoadingComplete(hasMore);
            }
        };

        @Override
        public void onGetTopicDiscussListError(int transactionId, int errCode, String err) {
            if (mTid == transactionId && mCurrentPage == 1) {
                if (errCode == XoneServiceCode.NETWORK_ERR_COMMON) {
                    mLoadingList.onNoNetwork();
                } else {
                    mLoadingList.onLoadingError();
                }
            }else{
                Toast.makeText(getActivity(), err, Toast.LENGTH_SHORT).show();
                mLoadingList.onLoadingComplete(false);
            }
        };
    };

    @Override
    public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
        StringBuilder where = new StringBuilder();
        int group;
        switch (mType) {
            case topic_discuss:
                group = ManagerAppInfo.GROUP_TOPIC_INFO_LIST;
                where.append(AppInfoTable.C_SORTTYPE).append("=").append(mTopicId).append(" AND ");
                break;
            case guess_discuss:
                group = ManagerAppInfo.GROUP_GUESS_DISCUSS_LIST;
                break;
            case pop_discuss:
            default:
                group = ManagerAppInfo.GROUP_POP_DISCUSS_LIST;
                break;
        }
        where.append(AppInfoTable.C_INFOGROUP).append("=").append(group).append(" AND ")
                .append(AppInfoTable.C_ACCOUNT).append("='")
                .append(ManagerAccount.getInstance().getCurrentAccountId()).append("'");
        return new CursorLoader(getActivity(), AppInfoTable.CONTENT_URI, ManagerAppInfo.Projection,
                where.toString(), null, null);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
        mAdapter.swapCursor(cursor);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> arg0) {
        mAdapter.swapCursor(null);
    }
}
